package com.xwaiy.xwaiyrpc.protocol;

import com.xwaiy.xwaiyrpc.model.RpcRequest;
import com.xwaiy.xwaiyrpc.model.RpcResponse;
import com.xwaiy.xwaiyrpc.serializer.Serializer;
import com.xwaiy.xwaiyrpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/**
 * 解码器
 * @Author Xwaiy
 * @Date 2025/8/29 11:59
 **/
public class Decoder {

    public static ProtocolMessage<?> decode(Buffer buffer) throws IOException {
        ProtocolMessage.Header header = new ProtocolMessage.Header();
        byte magic = buffer.getByte(0);
        // 校验
        if (magic != ProtocolConstant.PROTOCOL_MAGIC) {
            throw new IOException("Invalid protocol magic");
        }
        header.setMagic(magic);
        header.setVersion(buffer.getByte(1));
        header.setSerializer(buffer.getByte(2));
        header.setType(buffer.getByte(3));
        header.setStatus(buffer.getByte(4));
        header.setRequestId(buffer.getLong(5));
        header.setBodyLength(buffer.getInt(13));
        // 粘包
        byte[] body = buffer.getBytes(17,17+header.getBodyLength());
        // 消息体
        SerializerEnum serializerEnum = SerializerEnum.getEnumByKey(header.getSerializer());
        if (serializerEnum == null) {
            throw new IOException("Unknown serializer");
        }
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());
        TypeEnum typeEnum = TypeEnum.getEnumByKey(header.getType());
        if (typeEnum == null) {
            throw new IOException("Unknown type");
        }

        switch (typeEnum) {
            case REQUEST:
                RpcRequest req = serializer.deserialize(body, RpcRequest.class);
            case RESPONSE:
                RpcResponse resp = serializer.deserialize(body, RpcResponse.class);
            case HEART_BEAT:
            case OTHERS:
            default:
                throw new IOException("暂不支持该消息类型");
        }

    }
}
